package com.haorui.lygyd.controller;

import com.alibaba.fastjson.JSONObject;
import com.haorui.base.core.exception.BusinessException;
import com.haorui.base.core.utils.LoginUtil;
import com.haorui.base.system.dto.AccountDto;
import com.haorui.base.system.entity.JiekouEntity;
import com.haorui.base.system.service.AccountService;
import com.haorui.base.system.service.JiekouService;
import com.haorui.baseutil.utils.EmojiFilter;
import com.haorui.lygyd.authority.authentication.AccountAuthenticationToken;
import com.haorui.lygyd.authority.authentication.MemberAuthenticationToken;
import com.haorui.lygyd.authority.jwt.JwtTokenUtil;
import com.haorui.lygyd.authority.service.AccountDetailService;
import com.haorui.lygyd.employeemanager.dto.MemberDto;
import com.haorui.lygyd.employeemanager.entity.MemberEntity;
import com.haorui.lygyd.employeemanager.service.MemberService;
import com.haorui.lygyd.wxapi.common.CommonUtil;
import com.haorui.lygyd.wxapi.dto.*;
import com.haorui.lygyd.wxapi.entity.WXUserInfoEntity;
import com.haorui.lygyd.wxapi.service.WXMemberService;
import com.haorui.lygyd.wxapi.service.WXPublicService;
import com.haorui.lygyd.wxapi.service.WXUserInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2017/8/10
 * 时间: 16:16
 * 功能：授权
 */
@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private AccountDetailService accountDetailService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    AccountService accountService;
    @Autowired
    JiekouService jiekouService;
    @Autowired
    WXUserInfoService wxUserInfoService;
    @Autowired
    WXMemberService wxMemberService;
    @Autowired
    MemberService memberService;
    @Autowired
    WXPublicService wxPublicService;

    @RequestMapping(value = "/auth/login", method = RequestMethod.POST)
    public ResponseEntity loginAuth(@RequestBody AccountDto accountDto) {
        if (accountDto == null) {
            return null;
        }
        try {//你微信登录是这个接口？恩
            AccountAuthenticationToken upToken = new AccountAuthenticationToken(accountDto.getUserName(), accountDto.getPassword());
            Authentication authentication = authenticationManager.authenticate(upToken);
            return ResponseEntity.ok(authentication.getDetails());
        } catch (Exception e) {
            Map map = new HashMap();
            if (e instanceof BadCredentialsException) {
                map.put("message", "您的账号或密码错误!");
            } else if (e instanceof LockedException) {
                map.put("message", "账号已被锁定!");
            } else {
                map.put("message", "系统错误，联系管理员!");
            }
            return ResponseEntity.badRequest().body(map);
        }

    }


    @ApiOperation(value = "注销", notes = "返回实体列表", position = 2)
    @RequestMapping(value = "/auth/loginOut", method = RequestMethod.GET)
    public void loginOut(HttpServletRequest request) {

        HttpSession session = request.getSession();
        session.removeAttribute(LoginUtil.getLoginAccounName());
    }


    @ApiOperation(value = "微信openID授权获取", notes = "返回用户授权信息", position = 2)
    @RequestMapping(value = "/auth/member", method = RequestMethod.GET)
    public WXUserInfoEntity wxLoginAuth(HttpServletResponse response, HttpServletRequest request) {
        String code = (String) request.getParameter("code");
        if (code == null) {
            return null;
        }
        JiekouEntity jiekouEntity = jiekouService.findOne("1");
        String appid = jiekouEntity.getXiaochengxuAppID();
        String appsecret = jiekouEntity.getXiaochengxuSecret();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=AppId&secret=AppSecret&js_code=CODE&grant_type=authorization_code";
        url = url.replace("AppId", appid)
                .replace("AppSecret", appsecret)
                .replace("CODE", code);
        JSONObject jsonTexts = CommonUtil.httpsRequest(url, "GET", null);
        String openid = null;
        if (jsonTexts.get("openid") != null) {
            openid = jsonTexts.get("openid").toString();
        }

        WXUserInfoEntity weixinUserInfoEntity = wxUserInfoService.wxgetweixinUserByOpenId(openid);
        if (weixinUserInfoEntity == null) {
            weixinUserInfoEntity = new WXUserInfoEntity();
            weixinUserInfoEntity.setOpenId(openid);
        }
        return weixinUserInfoEntity;
    }

    @ApiOperation(value = "微信会员注册", notes = "返回注册后的会员信息", position = 2)
    @RequestMapping(value = "/auth/member/reg", method = RequestMethod.POST)
    public MemberEntity regeistAuth(@RequestBody WXMemberRegisDto wxMemberRegisDto) throws BusinessException {
        return wxMemberService.wxzhuCe(wxMemberRegisDto);
    }

    //todo 微信小程序上线删除
    @ApiOperation(value = "查询微信会员", notes = "会员集合", position = 2)
    @RequestMapping(value = "/auth/wxmember/wxselectWeiXin/{openId}", method = RequestMethod.GET)
    public WXUserInfoEntity wxselectWeiXin(@PathVariable String openId) {
        return wxUserInfoService.wxgetweixinUserByOpenId(openId);
    }

    @RequestMapping(value = "/auth/member/dlogin", method = RequestMethod.POST)
    public ResponseEntity memberDLogin(@RequestBody WXMemberLoginDto wxMemberLoginDto) {
        if (wxMemberLoginDto == null) {
            return null;
        }
        MemberEntity memberEntity = wxMemberService.findMemberByShouJiHaoMa(wxMemberLoginDto.getShouJiHaoMa());
        if (memberEntity == null) {
            Map map = new HashMap();
            map.put("message", "账号不存在!");
            return ResponseEntity.badRequest().body(map);
        }
        try {
            MemberAuthenticationToken upToken = new MemberAuthenticationToken(memberEntity.getShouJiHaoMa(), memberEntity.getMiMa(), wxMemberLoginDto.getOpenId());
            Authentication authentication = authenticationManager.authenticate(upToken);
            return ResponseEntity.ok(authentication.getDetails());
        } catch (Exception e) {
            Map map = new HashMap();
            if (e instanceof BadCredentialsException) {
                map.put("message", "您的账号或密码错误!");
            } else if (e instanceof LockedException) {
                map.put("message", "账号已被锁定!");
            } else {
                map.put("message", "系统错误，联系管理员!");
            }
            return ResponseEntity.badRequest().body(map);
        }
    }

    @ApiOperation(value = "微信会员登录", notes = "返回登录后的会员信息", position = 2)
    @RequestMapping(value = "/auth/member/login", method = RequestMethod.POST)
    public ResponseEntity memberLogin(@RequestBody WXMemberLoginDto wxMemberLoginDto) throws BusinessException {
        if (wxMemberLoginDto == null) {
            return null;
        }
        try {
            MemberAuthenticationToken upToken = new MemberAuthenticationToken(wxMemberLoginDto.getShouJiHaoMa(), wxMemberLoginDto.getMiMa(), wxMemberLoginDto.getOpenId());
            Authentication authentication = authenticationManager.authenticate(upToken);
            return ResponseEntity.ok(authentication.getDetails());
        } catch (Exception e) {
            e.printStackTrace();
            Map map = new HashMap();
            if (e instanceof BadCredentialsException) {
                map.put("message", "您的账号或密码错误!");
            } else if (e instanceof LockedException) {
                map.put("message", "账号已被锁定!");
            } else {
                map.put("message", "系统错误，联系管理员!");
            }
            return ResponseEntity.badRequest().body(map);
        }

    }


    @ApiOperation(value = "微信用户信息存库", notes = "返回登录后的会员信息", position = 2)
    @RequestMapping(value = "/auth/weixinuser", method = RequestMethod.POST)
    public void weixinUserSave(@RequestBody WXUserInfoDto wxUserInfoDto) {
        WXUserInfoEntity wxUserInfoEntity = wxUserInfoService.wxgetweixinUserByOpenId(wxUserInfoDto.getOpenId());
        if (wxUserInfoEntity == null) {
            System.out.println("新的微信用户注册" + wxUserInfoDto.getNickname() + ",openId:" + wxUserInfoDto.getOpenId());
            wxUserInfoDto.setNickname(EmojiFilter.filterEmoji(wxUserInfoDto.getNickname()));
            wxUserInfoService.save(wxUserInfoDto.buildPO());
        }
    }

    @ApiOperation(value = "微信获取验证码", notes = "无返回值", position = 2)
    @RequestMapping(value = "/auth/getYanZhengMa/{shoujihao}", method = RequestMethod.GET)
    public void getYanZhengMa(@PathVariable String shoujihao) throws BusinessException {
        wxMemberService.wxgetYanZhengMa(shoujihao);
    }

    @ApiOperation(value = "修改支付宝", position = 2)
    @RequestMapping(value = "/auth/alipay", method = RequestMethod.POST)
    public MemberEntity statistics(@RequestBody MemberDto dto) {
        MemberEntity entity = memberService.findOne(dto.getId());
        entity.setAlipay(dto.getAlipay());
        return memberService.save(entity);
    }

    @ApiOperation(value = "效验推荐人", notes = "无返回值", position = 2)
    @RequestMapping(value = "/auth/vaildtjr/{tuijianren}", method = RequestMethod.GET)
    public String vaildTuiJianRen(@PathVariable String tuijianren) throws BusinessException {
        MemberEntity memberEntity = wxMemberService.findMemberByShouJiHaoMa(tuijianren);
        if (memberEntity == null) {
            throw new BusinessException("推荐人填写错误");
        }
        return "ok";
    }

    @ApiOperation(value = "忘记密码", notes = "返回确认登录后的会员信息", position = 2)
    @RequestMapping(value = "/auth/wxforgetMiMa", method = RequestMethod.POST)
    public MemberEntity wxforgetMiMa(@RequestBody WXMemberForgetDto dto) throws BusinessException {
        return wxMemberService.wxforgetMiMa(dto);
    }

    @ApiOperation(value = "验证验证码", notes = "返回true或fasle", position = 2)
    @RequestMapping(value = "/auth/wxcheckYanzhengma/{shoujihaoma}/{yanzhengma}", method = RequestMethod.GET)
    public Boolean wxcheckYanzhengma(@PathVariable String shoujihaoma, @PathVariable String yanzhengma) {
        return wxMemberService.checkYanzhengma(shoujihaoma, yanzhengma);
    }

    @ApiOperation(value = "修改", notes = "返回确认登录后的会员信息", position = 2)
    @RequestMapping(value = "/auth/updatePass", method = RequestMethod.POST)
    public MemberEntity updatePass(@RequestBody WXMemberUpdatePassDto dto) throws BusinessException {
        return wxMemberService.updatePass(dto);
    }
}
